package com.example.test02;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class ActRequestActivity extends AppCompatActivity implements View.OnClickListener {

     static final String request = "发送到下一个页面";
    TextView textResponse;

    ActivityResultLauncher<Intent> register;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_act_request);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //设置初始值
        TextView textView = findViewById(R.id.tv_request);
        textResponse = findViewById(R.id.tv_response);
        textView.setText("待发送的数据："+request);
        //监听按钮
        findViewById(R.id.btn_request).setOnClickListener(this);

        //创建注册器
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent data = result.getData();
            if (data != null && result.getResultCode() == Activity.RESULT_OK) {
                //拿到传来的值
                Bundle extras = data.getExtras();
                String responseTime = extras.getString("response_time");
                String responseContent = extras.getString("response_content");
                textResponse.setText("时间：" + responseTime + "\n" + "内容：" + responseContent);
            }
        });


    }

    @Override
    public void onClick(View v) {
        //创建意图对象，向接收端发送数据
        Intent intent = new Intent(this, ActResponseActivity.class);
        //创建包裹
        Bundle bundle = new Bundle();
        bundle.putString("request_time",String.valueOf(System.currentTimeMillis()));
        bundle.putString("request_content",request);
        intent.putExtras(bundle);
        //发送
        register.launch(intent);
    }

}